package com.dz.controller.visitor;

import com.dz.annotation.OperationLog;
import com.dz.bean.Rate;
import com.dz.service.RateService;
import com.dz.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/v/rate")
@CrossOrigin
public class RateVisitorController {

    @Autowired
    private RateService rateService;

    @PostMapping("/add")
    @OperationLog("进行评分")
    public ResponseEntity<Result> add(@RequestBody Rate rate) {
        try {
            // 检查必要参数
            if (rate.getVisitorId() == null) {
                return ResponseEntity.badRequest().body(Result.error(500,"游客ID不能为空"));
            }
            if (rate.getGuideId() == null) {
                return ResponseEntity.badRequest().body(Result.error(500,"地陪ID不能为空"));
            }
            if (rate.getRates() == null || rate.getRates() < 1 || rate.getRates() > 5) {
                return ResponseEntity.badRequest().body(Result.error(500,"评分必须在1-5之间"));
            }

            // 设置创建时间
            rate.setCreateTime(LocalDateTime.now());
            boolean result = rateService.addRate(rate);
            return ResponseEntity.ok(Result.success(result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Result.error(500,"评分添加失败: " + e.getMessage()));
        }
    }

    @GetMapping("/getRateByGuideId")
    public ResponseEntity<Result> getRateByGuideId(@RequestParam("guideId") Integer guideId) {
        try {
            if (guideId == null) {
                return ResponseEntity.badRequest().body(Result.error(500,"地陪ID不能为空"));
            }
            Double result = rateService.getRateByGuideId(guideId);
            // 如果没有评分记录，返回0.0而不是null
            if (result == null) {
                result = 0.0;
            }
            return ResponseEntity.ok(Result.success(result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Result.error(500,"获取评分失败: " + e.getMessage()));
        }
    }

    @GetMapping("/checkRateByVisitorAndGuide")
    public ResponseEntity<Result> checkRateByVisitorAndGuide(
            @RequestParam("visitorId") Integer visitorId,
            @RequestParam("guideId") Integer guideId) {
        try {
            List<Rate> result = rateService.getRateByVisitorAndGuide(visitorId, guideId);
            boolean isRated = result != null && !result.isEmpty();
            return ResponseEntity.ok(Result.success(isRated));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Result.error(500, "检查评分状态失败: " + e.getMessage()));
        }
    }
}
